import numpy as np
from filterpy.kalman import KalmanFilter


def linear_assignment(cost_matrix):
    try:
        import lap

        _, x, y = lap.lapjv(cost_matrix, extend_cost=True)
        return np.array([[y[i], i] for i in x if i >= 0])  #
    except ImportError:
        from scipy.optimize import linear_sum_assignment

        x, y = linear_sum_assignment(cost_matrix)
        return np.array(list(zip(x, y)))


def get_distance(d, t):
    return np.linalg.norm(np.subtract(d[:, np.newaxis, :], t), axis=2)


def convert_xyz_to_z(xyz):
    """Converts 3D position [x, y, z] into the measurement space."""
    return np.array([[xyz[0]], [xyz[1]], [xyz[2]]]).reshape((3, 1))


def convert_x_to_xyz(x):
    """Converts the state vector into 3D position [x, y, z]."""
    return np.array([x[0], x[1], x[2]]).reshape((1, 3))


class KalmanBoxTracker3D(object):
    """This class represents the internal state of individual tracked objects in 3D."""

    count = 0

    def __init__(self, xyz):
        """Initializes a tracker using initial position."""
        self.kf = KalmanFilter(dim_x=6, dim_z=3)
        self.kf.F = np.array(
            [
                [1, 0, 0, 1, 0, 0],  # State transition matrix
                [0, 1, 0, 0, 1, 0],
                [0, 0, 1, 0, 0, 1],
                [0, 0, 0, 1, 0, 0],
                [0, 0, 0, 0, 1, 0],
                [0, 0, 0, 0, 0, 1],
            ]
        )
        self.kf.H = np.array(
            [
                [1, 0, 0, 0, 0, 0],  # Measurement function
                [0, 1, 0, 0, 0, 0],
                [0, 0, 1, 0, 0, 0],
            ]
        )

        self.kf.P *= 10.0  # Initial state uncertainty
        self.kf.P[3:, 3:] *= 1000.0  # Velocity uncertainty
        self.kf.Q[-3:, -3:] *= 0.01  # Process uncertainty
        self.kf.R *= 1.5  # Measurement uncertainty

        self.kf.x[:3] = convert_xyz_to_z(xyz)

        self.time_since_update = 0
        self.id = KalmanBoxTracker3D.count
        KalmanBoxTracker3D.count += 1
        self.hits = 0
        self.hit_streak = 0
        self.age = 0

    def update(self, xyz):
        """Updates the state vector with observed 3D position."""
        self.time_since_update = 0
        self.hits += 1
        self.hit_streak += 1
        self.kf.update(convert_xyz_to_z(xyz))

    def predict(self):
        """Advances the state vector and returns the predicted 3D position estimate."""
        self.kf.predict()
        self.age += 1
        if self.time_since_update > 0:
            self.hit_streak = 0
        self.time_since_update += 1
        return convert_x_to_xyz(self.kf.x)

    def get_state(self):
        """Returns the current 3D position estimate."""
        return convert_x_to_xyz(self.kf.x)


def associate_detections_to_trackers(detections, trackers, dist_thresh=1.0):
    """
    Assigns detections to tracked object (both represented as 3D points)
    Returns 3 lists of matches, unmatched_detections and unmatched_trackers
    """
    if len(trackers) == 0:
        return (
            np.empty((0, 2), dtype=int),
            np.arange(len(detections)),
            np.empty((0, 1), dtype=int),
        )

    distance_matrix = get_distance(detections, trackers)

    if min(distance_matrix.shape) > 0:
        a = (distance_matrix < dist_thresh).astype(np.int32)
        if a.sum(1).max() == 1 and a.sum(0).max() == 1:
            matched_indices = np.stack(np.where(a), axis=1)
        else:
            matched_indices = linear_assignment(distance_matrix)
    else:
        matched_indices = np.empty(shape=(0, 2))

    unmatched_detections = []
    for d, det in enumerate(detections):
        if d not in matched_indices[:, 0]:
            unmatched_detections.append(d)
    unmatched_trackers = []
    for t, trk in enumerate(trackers):
        if t not in matched_indices[:, 1]:
            unmatched_trackers.append(t)

    # filter out matched with low IOU
    matches = []
    for m in matched_indices:
        if distance_matrix[m[0], m[1]] < dist_thresh:
            matches.append(m.reshape(1, 2))
        else:
            unmatched_detections.append(m[0])
            unmatched_trackers.append(m[1])

    if len(matches) == 0:
        matches = np.empty((0, 2), dtype=int)
    else:
        matches = np.concatenate(matches, axis=0)

    return matches, np.array(unmatched_detections), np.array(unmatched_trackers)


class Sort3D:
    def __init__(self, max_age=10, min_hits=2, dist_thresh=1.0):
        """Sets key parameters for SORT in 3D"""
        self.max_age = max_age
        self.min_hits = min_hits
        self.dist_thresh = dist_thresh
        self.trackers = []
        self.frame_count = 0

    def update(self, dets=np.empty((0, 3))):
        """
        Params:
          dets - a numpy array of detections in the format [[x,y,z],[x,y,z],...]
        Requires: this method must be called once for each frame even with empty detections
                  (use np.empty((0, 5)) for frames without detections).
        Returns the a similar array, where the last column is the object ID.

        NOTE: The number of objects returned may differ from the number of detections provided.
        """
        self.frame_count += 1
        # Get predicted locations from existing trackers.
        trks = np.zeros((len(self.trackers), 3))
        to_del = []
        ret = []
        for t, trk in enumerate(trks):
            pos = self.trackers[t].predict()[0]
            trk[:] = pos
            if np.any(np.isnan(pos)):
                to_del.append(t)

        trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
        for t in reversed(to_del):
            self.trackers.pop(t)

        matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(
            dets, trks, self.dist_thresh
        )

        # update matched trackers with assigned detections
        for m in matched:
            self.trackers[m[1]].update(dets[m[0], :])

        # create and initialise new trackers for unmatched detections
        for i in unmatched_dets:
            trk = KalmanBoxTracker3D(dets[i, :])
            self.trackers.append(trk)
        i = len(self.trackers)
        for trk in reversed(self.trackers):
            d = trk.get_state()[0]
            if (trk.time_since_update < 1) and (
                trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits
            ):
                ret.append(
                    np.concatenate((d, [trk.id + 1])).reshape(1, -1)
                )  # +1 as MOT benchmark requires positive
            i -= 1
            # remove dead tracklet
            if trk.time_since_update > self.max_age:
                self.trackers.pop(i)
        if len(ret) > 0:
            return np.concatenate(ret)
        return np.empty((0, 4))
